package fr.hoteia.appengine.archetype.server.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import com.google.appengine.api.memcache.stdimpl.GCacheFactory;

import fr.hoteia.appengine.archetype.server.service.Manager;

/**
 * Base class for Business Services - use this class for utility methods and
 * generic CRUD methods.
 * 
 * <p><a href="BaseManager.java.html"><i>View Source</i></a></p>
 *
 * @author Denis GOSSET <a href="http://www.hoteia.com"><i>Hoteia.com</i></a>
 * 
 */
public class BaseManager implements Manager {
	
	private CacheManager cacheManager;
	private CacheFactory cacheFactory;
	
	public CacheManager getCacheManager() {
		if(cacheManager == null) {
			cacheManager = CacheManager.getInstance();
		}
    	return cacheManager;
	}
	
	public CacheFactory getCacheFactory() {
		if(cacheFactory == null) {
			try {
				cacheFactory = getCacheManager().getCacheFactory();
			} catch (CacheException e) {
				e.printStackTrace();
			}
		}
    	return cacheFactory;
	}
    
    @SuppressWarnings("unchecked")
	public Cache getCache(String cacheType) {
		Cache cache = getCacheManager().getCache(cacheType);
		if(cache == null) {
			try {
				Map props = new HashMap();
				props.put(GCacheFactory.EXPIRATION_DELTA, 3600);
				cache = getCacheFactory().createCache(props);
			} catch (CacheException e) {
				e.printStackTrace();
			}
		}
    	return cache;
	}
    
}
